package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.service.IUserFavorRedisService;
import cn.wolfcode.wolf2w.redis.vo.StatisticsVO;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.util.RedisKeysStandard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* 攻略明细服务接口实现
*/
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRepository repsitory;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IUserFavorRedisService userFavorRedisService;



    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        repsitory.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        repsitory.save(strategy);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable, query,Strategy.class);
    }

    @Override
    public Page<Strategy> queryForApi(StrategyQuery qo) {
        Query query = new Query();
        // 目的地的限制
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        // 主题的限制
        if (StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }
        query.addCriteria(Criteria.where("state").is(Strategy.STATE_PUBLISH));
        Pageable pageable = PageRequest.of(qo.getCurrentPage()- 1,qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template,pageable, query,Strategy.class);
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        //保存与修改之前的字段操作

        //目的地名称与id保存以及分类的名称，根据catalogId分类的id查询
        StrategyCatalog catalog = strategyCatalogService.get(strategy.getCatalogId());
        strategy.setDestId(catalog.getDestId());
        strategy.setDestName(catalog.getDestName());
        strategy.setCatalogName(catalog.getName());

        // 判断是否是国外 然后设置
        List<Destination> toasts = destinationService.findByParentId(strategy.getDestId());
        if (toasts != null && toasts.size() > 0) {
            Destination destination = toasts.get(0);
            if ("中国".equals(destination.getName())) {
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }else {
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }
        }
        // 设置主题的名字
        StrategyTheme strategyTheme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(strategyTheme.getName());

        if(StringUtils.hasLength(strategy.getId())){
            //update
            Strategy strategyInDB = strategyService.get(strategy.getId());
            // 设置前端没有的数据
            strategy.setCreateTime(strategyInDB.getCreateTime());
            strategy.setFavornum(strategyInDB.getFavornum());
            strategy.setViewnum(strategyInDB.getViewnum());
            strategy.setReplynum(strategyInDB.getReplynum());
            strategy.setSharenum(strategyInDB.getSharenum());
            strategy.setThumbsupnum(strategyInDB.getThumbsupnum());
            this.update(strategy);
        }else{
            //save
            // 只有在保存的时候需要创建时间
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }
    }

    @Override
    public void updateStateById(String id, int state) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("state", state);
        template.updateMulti(query, update, Strategy.class);
    }

    @Override
    public List<Strategy> queryByCatalogId(String catalogId) {
        return repsitory.findByCatalogId(catalogId);
    }

    @Override
    public List<Strategy> queryStrategyTop3(String destId) {
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC,"viewnum");
        List<Strategy> list = repsitory.findByDestId(destId, pageable);
        return list;
    }

    @Override
    public void updateStatisticsVO(StatisticsVO vo) {
        Query query = new Query();
        if (StringUtils.hasLength(vo.getStrategyId())) {
            query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        }
        /**"viewnum": NumberInt("648738"),
         "replynum": NumberInt("87"),
         "favornum": NumberInt("45320"),
         "sharenum": NumberInt("14970"),
         "thumbsupnum": NumberInt("281"),*/
        Update update = new Update();
        update.set("viewnum", vo.getViewnum());
        update.set("replynum", vo.getReplynum());
        update.set("favornum", vo.getFavornum());
        update.set("sharenum", vo.getSharenum());
        update.set("thumbsupnum", vo.getThumbsupnum());
        template.updateMulti(query, update, Strategy.class);
    }

    @Override
    public List<Strategy> findByDestId(String destId) {
        return repsitory.findByDestId(destId, null);
    }

    @Override
    public List<Strategy> getCollectionsById(String userId) {
        List<Strategy> list = new ArrayList<>();
        // 根据用户id查询redis中得到用户收藏的攻略文章id
        List<String> favorList = userFavorRedisService.getFavorList(userId);
        if (favorList.size() <= 0) {
            return null;
        }
        list = repsitory.findByIdIn(favorList);
        return list;
    }
}
